package com.wcity.manage.service.impl;

import com.alibaba.fastjson.JSON;
import com.wcity.manage.common.utils.DateUtil;
import com.wcity.manage.dao.dal.model.PageModel;
import com.wcity.manage.dao.mapper.BlockMapper;
import com.wcity.manage.dao.mapper.PropertyPayMapper;
import com.wcity.manage.dao.model.Block;
import com.wcity.manage.dao.model.PropertyPay;
import com.wcity.manage.service.property.PropertyPayService;
import org.apache.commons.collections.map.HashedMap;
import org.apache.poi.hssf.usermodel.HSSFDateUtil;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.text.DateFormat;
import java.text.DecimalFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 业主缴费数据管理模块
 * Created by zm on 2016/12/10.
 */
@Service
public class PropertyPayServiceImpl implements PropertyPayService {

    private final Logger logger = LoggerFactory.getLogger(PropertyPayServiceImpl.class);
    @Resource private PropertyPayMapper propertyPayMapper;
    @Resource private BlockMapper blockMapper;

    /**
     * 分页获取表单数据
     * @param page
     * @return
     */
    @Override
    public List<PropertyPay> getUserListPage(PageModel<PropertyPay> page) {
        return propertyPayMapper.findListPage( page );
    }

    /**
     * 获取小区名称
     * @param id
     * @return
     */
    @Override
    public List<Block> getblockName(int id) {
        return propertyPayMapper.getblockName(id);
    }

    /**
     * 添加
     * @param pay
     * @return
     */
    @Override
    public int addPaylist(PropertyPay pay) {
        return propertyPayMapper.insert(pay);
    }

    /**
     * 删除
     * @param id
     * @return
     */
    @Override
    public int delectPay(String id) {
        return propertyPayMapper.delete(id);
    }

    /**
     * 根据id获取缴费信息
     * @param id
     * @return
     */
    @Override
    public PropertyPay getPayInfo(String id) {
        return propertyPayMapper.getPayInfo(id);
    }

    /**
     * 更新缴费信息
     * @param pay
     * @return
     */
    @Override
    public int updateUser( PropertyPay pay ) {
        return propertyPayMapper.update(pay);
    }

    /**
     * 判断是否存在该缴费账户
     * @param payUser
     * @param payUserTel
     * @param
     * @return
     */
    @Override
    public int selectCount(String payUser, String payUserTel) {
        return propertyPayMapper.selectCount ( payUser , payUserTel );
    }

    /**
     * 获取一年的账单
     * @param pageModel
     * @return
     */
    @Override
    public List<PropertyPay> getIPayList(PageModel pageModel) {
        return propertyPayMapper.getIPayList (pageModel);
    }

    /**
     * 获取一年的费用
     * @param payUser
     * @param payUserTel
     * @param year
     * @return
     */
    @Override
    public PropertyPay getPayFee(String payUser , String payUserTel  ,String year) {
        return propertyPayMapper.getPayFee ( payUser , payUserTel , year) ;
    }

    /**
     * 获取物业费账单详情
     * @param payId
     * @return
     */
    @Override
    public PropertyPay getIPayInfo(String payId) {
        return propertyPayMapper.getPayInfo(payId);
    }

    /**
     * 查询缴费数据的所有数据
     * @return
     */
    @Override
    public List<PropertyPay> selectPayModel(PropertyPay propertyPay) {
        return propertyPayMapper.selectPayModel(propertyPay);
    }

    /**
     * 批量导入（只使用2003版的excel）
     * @param target
     * @return
     */
    @Override
    @Transactional
    public String excelToDb(File target , int userId , String workNo) {
        try{
            PropertyPay propertyPay = new PropertyPay();
            FileInputStream fi = new FileInputStream(target);
            Workbook wb = new HSSFWorkbook(fi);
            Sheet sheet = wb.getSheetAt(0);
            int rowNum = sheet.getLastRowNum() + 1;  //获取总的行数
            for (int i = 1; i < rowNum; i++) {
                Row row = sheet.getRow(i); //获取改行
                Block count = propertyPayMapper.selectBlockName(row.getCell(0).getStringCellValue(),userId );
                if(count==null) return "小区("+row.getCell(0).getStringCellValue()+")不存在，请先添加小区";
                if (row.getCell(0) == null) return "小区名称为空";
                if (row.getCell(2) == null) return "小区地址为空";
                if (row.getCell(3) == null) return "住户姓名为空";
                if (row.getCell(4) == null) return "联系方式为空";
                if (row.getCell(5) == null) return "缴费类型错误";
                if (row.getCell(6).getCellType() != 0) return "收费标准错误";
                if (row.getCell(7).getCellType() != 0) return "应缴金额错误";
                if (row.getCell(8).getCellType() != 0) return "收费日期错误";
                if (row.getCell(9).getCellType() != 0) return "费用开始日期错误";
                if (row.getCell(10).getCellType() != 0) return "费用结束日期错误";
                if (!row.getCell(11).getStringCellValue().equals("正常") && !row.getCell(11).getStringCellValue().equals("欠费")) return "状态请输入正常或欠费";
            }
            for (int i = 1; i < rowNum; i++) {
                Row row = sheet.getRow(i); //获取改行
                int cellNum = row.getLastCellNum(); //获取总的列数少一
                row.getCell(1).setCellType(Cell.CELL_TYPE_STRING);
                row.getCell(2).setCellType(Cell.CELL_TYPE_STRING);
                row.getCell(4).setCellType(Cell.CELL_TYPE_STRING);
                    for (int j = 0; j < cellNum; j++) {
                        Cell cell = row.getCell(j); //获取该列
                        String cellValue = null;
                        switch (cell.getCellType()) { //判断excel单元格内容的格式，并对其进行转换，以便插入数据库
                            case 0:
                                cellValue = String.valueOf((int) cell.getNumericCellValue());
                                if (HSSFDateUtil.isCellDateFormatted(cell)) {
                                    //用于转化为日期格式
                                    Date d = cell.getDateCellValue();
                                    DateFormat formater = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                                    cellValue = formater.format(d);
                                } else {
                                    // 用于格式化数字，只保留数字的整数部分
                                    /*DecimalFormat df = new DecimalFormat("########");
                                    cellValue = df.format(cell.getNumericCellValue());*/
                                    cellValue = cell.getNumericCellValue()+"";
                                    System.out.println(cellValue);
                                }
                                break;
                            case 1:
                                cellValue = cell.getStringCellValue();
                                break;
                            case 2:
                                break;
                            case 3:
                                cellValue = "";
                                break;
                            case 4:
                                cellValue = String.valueOf(cell.getBooleanCellValue());
                                break;
                            case 5:
                                cellValue = String.valueOf(cell.getErrorCellValue());
                                break;
                        }


                        switch (j) {
                            case 0:
                                try {
                                    Block count = propertyPayMapper.selectBlockName( cellValue,userId );
                                    if(count==null) return "小区("+cellValue+")不存在，请先添加小区";
                                    propertyPay.setPayBlockName(cellValue);
                                    propertyPay.setBlockId(count.getId());
                                }catch (Exception e) {
                                    e.printStackTrace();
                                    logger.error(e.getMessage(),e);
                                }
                                break;
                            case 1:
                                propertyPay.setPayFeeNum(cellValue);
                                break;
                            case 2:
                                propertyPay.setPayUserAddr(cellValue);
                                break;
                            case 3:
                                propertyPay.setPayUser(cellValue);
                                break;
                            case 4:
                                propertyPay.setPayUserTel(cellValue);
                                break;
                            case 5:
                                propertyPay.setPayType(cellValue);

                                break;
                            case 6:
                                propertyPay.setPayCharge(cellValue);
                                break;
                            case 7:
                                propertyPay.setPayMoney(cellValue);
                                break;
                            case 8:
                                try {
                                    Date now = DateUtil.strToDateTime(cellValue);
                                    propertyPay.setPayDate(now);
                                } catch (ParseException e) {
                                    e.printStackTrace();
                                    logger.error(e.getMessage(),e);
                                }
                                break;
                            case 9:
                                try {
                                    Date now = DateUtil.strToDateTime(cellValue);
                                    propertyPay.setPayStartDate(now);
                                } catch (ParseException e) {
                                    e.printStackTrace();
                                }
                                break;
                            case 10:
                                try {
                                    Date now = DateUtil.strToDateTime(cellValue);
                                    propertyPay.setPayEndDate(now);
                                } catch (ParseException e) {
                                    e.printStackTrace();
                                }
                                break;
                            case 11:
                                propertyPay.setPayState(cellValue);
                                break;
                            case 12:
                                propertyPay.setPayRemark(cellValue);
                                break;
                        }
                    }
                    propertyPay.setPayProName(workNo);
                    propertyPay.setUserId(userId);
                    propertyPay.setPayUpdate(new Date());
                    propertyPay.setCreateTime(new Date());
                    int success = propertyPayMapper.insert(propertyPay);
                    if( success == 0 ) return "插入失败";
            }
        }catch (Exception e){
            logger.error(e.getMessage(),e);
            e.printStackTrace();
            return "服务器异常";
        }
        return "";
    }

    /**
     * 获取缴费数据表
     * @param pageModel
     * @param payUser
     * @param payUserTel
     * @param type
     * @return
     */
    @Override
    public Map<String, Object> getYeanList(PageModel pageModel, String payUser, String payUserTel, String type) {

        Map<String,Object> map = null;
        Map<String,Object> map2 = null;
        Map<String,Object> map1 = new HashMap();

        PropertyPay pay = new PropertyPay();
        pay.setPayUser( payUser );
        pay.setPayUserTel( payUserTel );

        Calendar cal = Calendar.getInstance();
        int year = cal.get(Calendar.YEAR);

        pay.setId( year );
        pageModel.setParams( pay );

        switch ( type )
        {
            case "0"://0为本年的缴费数据
                map = new HashMap<>();
                map.put(year+"",propertyPayMapper.getIPayList (pageModel));
                map1.put("list",map);
                break;
            case "1"://1为历年的缴费数据
                List<PropertyPay> years = propertyPayMapper.getYearsList(payUser,payUserTel,year);
                SimpleDateFormat formatter = new SimpleDateFormat("yyyy");
                map2 = new HashMap<>();
                for ( PropertyPay yearList : years ) {
                    String dateString2 = formatter.format( yearList.getPayStartDate() );
                    map2.put(dateString2,dateString2);
                }
                map = new HashMap<>();
                for( Map.Entry<String, Object> entry:map2.entrySet() ) {
                    List<Object> list = new ArrayList<>();
                    for ( PropertyPay yearList1 : years ) {
                        String dateString1 = formatter.format( yearList1.getPayStartDate() );
                        if( dateString1.equals(entry.getValue()) ){
                            list.add(yearList1);
                        }
                    }
                    map.put( entry.getKey(), list );
                }
                map1.put("list",map);
                System.out.println(JSON.toJSONString(map1,true));

                break;
        }
        return map1;
    }
}
